package org.jeecg.modules.lab.aop;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.lab.util.BeanUtils;
import org.jeecg.modules.lab.operation.entity.LabOperation;
import org.jeecg.modules.lab.operation.mapper.LabOperationMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;


/**
 * 系统日志：切面处理类
 * 留痕日志:记录所有修改操作对数据的改变
 */
//@Aspect
@Component
@Slf4j
public class SysLogAspects {

    @Autowired
    private LabOperationMapper labOperationMapper;

    //定义切点 @Pointcut
    //在注解的位置切入代码
//    @Pointcut("execution(* org.jeecg.modules.lab.*.service.*.*(..))")
//    public void logPoinCut() {
//    }

//    @Before("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint)  {

        //获取切入点的方法名
        String name = joinPoint.getSignature().getName();
        if (!name.startsWith("update")){
            return;
        }

        //获取请求参数中的对象
        Object[] args = joinPoint.getArgs();
        Object target = joinPoint.getTarget();
        Object invoke = null;//查询数据库的结果
        String tableId=null;

        try {
            Method getById = target.getClass().getMethod("getById", Serializable.class);
            Method getId = args[0].getClass().getMethod("getId");
            tableId = getId.invoke(args[0]).toString();
            invoke = getById.invoke(target, tableId);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        String changedFields = BeanUtils.getChangedFields(args[0], invoke);

        //获取用户信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getId();
        String username = loginUser.getUsername();

        String name1 = args[0].getClass().getName();

        //创建日志类
        LabOperation labOperation = new LabOperation();
        labOperation.setOperationDate(new Date());
        labOperation.setUserId(userId);
        labOperation.setTableId(tableId);
       labOperation.setTableName(name1);
        labOperation.setUserName(username);
        labOperation.setType("修改");
        labOperation.setDescription(changedFields);

        UUID uuid = UUID.randomUUID();
        labOperation.setId(uuid.toString());
        labOperationMapper.insert(labOperation);
    }
}